<template>
  <div class="refine_addauth">
    <h2 class="titleblue">{{title}}角色权限</h2>
    <div class="contant">
      <el-form ref="form" label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="roleName" class="select-width-220"></el-input>
        </el-form-item>
        <p>权限设置</p>
        <el-table ref="multipleTable" :data="menuArray" tooltip-effect="dark" style="width: 100%" border stripe>
          <el-table-column label="序号" width="60" align="center">
            <template slot-scope="scope">
              {{scope.$index < 9 ? '0' : ''}}{{scope.$index + 1}}
            </template>
          </el-table-column>
          <el-table-column prop="modal" label="系统模块" width="100" align="center">
            <template slot-scope="scope">
              {{scope.row.name}}
            </template>
          </el-table-column>
          <el-table-column prop="auth" label="权限" align="center">
            <template slot-scope="scope">

                <el-checkbox v-model="checkAll[scope.$index]" @change="value => handleCheckAll(scope.$index, value)">全选</el-checkbox>
                <template v-if="scope.row.subMenu.length > 0">
                  <template v-if="scope.row.subMenu.length > 0" v-for="(m2, index) in scope.row.subMenu">

                    <el-checkbox :label="m2.id" :key="index" :value="m2.checked" @change="(value) => menuChecked(scope.$index, m2.id, value)">{{m2.name}}</el-checkbox>

                    <el-checkbox v-for="(m3, index) in m2.subMenu" :label="m3.id" :key="m3.id" :value="m3.checked" @change="(value) => menuChecked(scope.$index, m3.id, value)">{{m3.name}}</el-checkbox>

                  </template>
                </template>


            </template>
          </el-table-column>
        </el-table>

        <el-form-item style="text-align: center;">
          <el-button @click="doSubmit" class="sure">保存</el-button>
          <el-button @click="cancel" class="cancel">取消</el-button>
        </el-form-item>
      </el-form>

    </div>
  </div>

</template>

<script>
  import * as userRoleService from '@/services/UserRoleService'
  import * as userMenuService from '@/services/UserMenuService'

  export default {
    props: ['roleData'],
    data:function () {
      return {
        roleName: '',
        time: '',
        // roleArray: [],
        menuArray: [],
        checkAll: [],
        title: ''
      }
    },
    created() {
      if(this.roleData){
        this.title = '编辑'
        this.roleName = this.roleData.name
      } else {
        this.title = '新建'
      }
      this.getData()
    },
    methods: {
      getData() {
        let roleData = this.roleData || {userMenus:[]}

        userMenuService.findAll().then(menuArray => {
          let l1 = menuArray.filter(m => m.parentId === 0).sort((a, b) => a.orderx > b.orderx)
          let checkArray = new Array(l1.length)
          l1.forEach((m1, index) => {
            let checked = true;
            m1.subMenu = menuArray.filter(m2 => m2.parentId === m1.id).sort((a, b) => a.orderx > b.orderx) || []

            m1.subMenu.forEach(m2 => {
              m2.checked = !!roleData.userMenus.find(um => um.id === m2.id)
              checked = checked && m2.checked
              m2.subMenu = menuArray.filter(m3 => {
                return m3.parentId === m2.id
              }) || []
              m2.subMenu.forEach(m3 => {
                m3.checked = !!roleData.userMenus.find(um => um.id === m3.id)
                checked = checked && m3.checked
              })
            })
            checkArray[index] = checked
          })
          this.menuArray = l1
          this.checkAll = checkArray
        })
      },
      checkResult(m1) {
        let checked = true;
        m1.subMenu.forEach(m2 => {
          checked = checked && m2.checked
          m2.subMenu.forEach(m3 => {
            checked = checked && m3.checked
          })
        })
        return checked
      },
      menuChecked(idx, id, value) {

        let m2Menus = this.menuArray[idx].subMenu
        let obj = m2Menus.find(m2 => m2.id === id)
        if (!obj) {
          for (let i = 0; i < m2Menus.length; i++) {
            obj = m2Menus[i].subMenu.find(m3 => m3.id === id)
            if (!!obj) {
              break;
            }
          }
        }
        if (!!obj) {
          obj.checked = value
        }
        this.checkAll[idx] = this.checkResult(this.menuArray[idx])
      },
      handleCheckAll(idx, val) {
        let row = this.menuArray[idx]
        row.subMenu.forEach(m2 => {
          m2.checked = val
          m2.subMenu.forEach(m3 => m3.checked = val)
        })
      },
      doSubmit(){
        if(!this.roleName){
          this.$alert('请输入角色名','提示')
          return false;
        }
        let roleData = {status: 0}
        if (this.roleData) {
          roleData = {...this.roleData}
        }
        roleData.userMenus = [];
        roleData.name = this.roleName
        this.menuArray.forEach(m1 => {
          let authCheck = false
          m1.subMenu.forEach(m2 => {
            if (m2.checked) {
              roleData.userMenus.push({id: m2.id})
              authCheck = true
            }
            m2.subMenu.forEach(m3 => {
              if (m3.checked) {
                roleData.userMenus.push({id: m3.id})
                authCheck = true
              }
            })
          })
          if (authCheck) {
            roleData.userMenus.push({id: m1.id})
          }
        })

        if (this.roleData) {
          userRoleService.update(roleData).then(() => {
            this.$alert('修改成功', {
              confirmButtonText: '确定',
              callback: action => {
                this.$emit('close');
              }
            })
          })
        } else {
          userRoleService.create(roleData).then(() => {
            this.$alert('添加成功', {
              confirmButtonText: '确定',
              callback: action => {
                this.$emit('close');
              }
            })
          })
        }

      },
      cancel(){
        this.$emit("cancel");
      },
    }
  };

</script>

<style lang="scss">

  .refine_addauth {
    width:100%;
    display: inline-block;

    .el-table{
      margin-bottom:50px;
    }
    .el-checkbox {
      float: left;
      margin-right: 15px;
      margin-left: 0px !important;
    }
    .el-form-item__label{
      text-align:left;
    }
  }

</style>
